<?php


namespace app\api\server\user;

use app\api\model\user\UserFollowApiModel;
use app\api\model\user\UserWriterApplyApiModel;
use app\api\model\user\UserWriterWaterApiModel;
use app\api\model\user\UserWriterWithdrawApiModel;
use app\api\ServerBase;
use app\api\validate\user\UserWriterVal;
use app\logic\model\ConfigLogicModel;
use app\logic\model\SettingModel;
use app\logic\model\UserFocus;
use app\logic\single\ConfigSingle;
use app\Request;
use app\api\model\OpusSeriesModel;
use app\api\model\order\OrderOpusModel;
use app\api\model\user\UserBankModel;
use app\api\model\UserModel;
use app\api\model\view\OpusNumber_opus_userView;
use Snow\Snow;
use think\facade\Db;
use think\facade\Cache;
class UserServer extends ServerBase
{
    protected $request;
    protected $model;
    /**
     * @var UserFollowApiModel
     */
    private $userFollowModel;
    /**
     * @var UserWriterApplyApiModel
     */
    private $userWriterApplyModel;
    /**
     * @var UserWriterWaterApiModel
     */
    private $userWriterWaterModel;
    /**
     * @var UserWriterWithdrawApiModel
     */
    private $UserWriterWithdrawModel;

    function __construct($request)
    {
        $this->request=$request;
        $this->param=$request->param();
        $this->userFollowModel = new UserFollowApiModel();
        $this->userWriterApplyModel = new UserWriterApplyApiModel();
        $this->userWriterWaterModel = new UserWriterWaterApiModel();
        $this->UserWriterWithdrawModel = new UserWriterWithdrawApiModel();
        $this->model=new UserModel();
    }

    function getUser(){
        $user = $this->request->user;
        unset($user['is_black'],$user['pid']);
        $this->getMessageCode('adminMessage.success.select',2);
        return $user;
    }
    function editUser(){
        $data['head_img'] = $this->param['head_img']??'';
        $data['nickname'] = $this->param['nickname']??'';
        if(empty($data['head_img'])){
            $this->ERROR='请上传头像';
            return false;
        }
        if(empty($data['nickname'])){
            $this->ERROR='请输入昵称';
            return false;
        }
        $this->model->where('id',$this->request->user_id)->save($data);
        return true;
    }
    function editWriter(){
        if($this->request->user['is_writer'] != 1){
            $this->ERROR='请先成为创作者';
            return false;
        }
        $data['writer_head_img'] = $this->param['writer_head_img']??'';
        $data['writer_name'] = $this->param['writer_name']??'';
        $data['introduction'] = $this->param['introduction']??'';
        if(empty($data['head_img'])){
            $this->ERROR='请上传头像';
            return false;
        }
        if(empty($data['nickname'])){
            $this->ERROR='请输入昵称';
            return false;
        }
        if(empty($data['introduction'])){
            $this->ERROR='请输入简介';
            return false;
        }
        $this->model->where('id',$this->request->user_id)->save($data);
        return true;
    }
    function getWriterList(){
        $where['is_writer'] = 1;
        $field="id,writer_name,writer_head_img,fans_num,introduction";
        [$page,$limit] = $this->getPage($this->request->param());
        [$list,$count] = $this->model->getList([],$where,$field,$page,$limit,'fans_num desc,id desc');

        foreach ($list as &$val){
            $val['is_follow'] = UserFollowApiModel::checkFollow($val['id'],$this->request->user_id);
        }
        $result['data']=$list;
        $result['count']=$count;
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }

    function getCollectorsList(){
        $this->request['is_collectors']=1;
        $this->request['cangjiaxiu']=1;//藏家秀列表接口的标识
        $field="id,nickname,avatar,autograph";
        $list=$this->model->getList($this->request,$field);
        if(is_array($list)){
            foreach ($list['data'] as $key=>&$val){
                //获取作品编码5个
                $where=array(
                    "owner_uid"=>$val['id']
                );
                $opusNumber=(new OpusNumber_opus_userView())->getList($where,"o.id as opus_number_id,o.opus_id,o.opus_title,o.opus_img",99999);
                $val['follow']=(new UserFocus())->checkFollowed($val['id']);
                $val['opusNumber']=[];
                if(is_array($opusNumber)){
                    $val['opusNumber']=$opusNumber['data'];
                }
            }
            unset($val);
        }
        show_json("code_common.success",$list);
    }
    
    function getWriterRate(){
        global $user;
        $writer_rate=$user['writer_rate'];
        if($writer_rate==-1){
            $writer_rate=(new SettingModel())->value('writer_rate');
        }
        show_json('code_common.success',round($writer_rate/100,2));
    }

    function follow(){
        $writer_id = $this->param['id']??0;
        if(empty($writer_id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        $writer = $this->model->isWriter($writer_id);
        if(empty($writer)){
            $this->ERROR='该用户不是创作者';
            return false;
        }
        $res = $this->userFollowModel->follow_op($this->request->user_id,$writer_id);
        if($res == 1){
            Db::name('user')->where('id',$writer_id)->inc('fans_num')->update();
        }else{
            Db::name('user')->where('id',$writer_id)->dec('fans_num')->update();
        }
        return true;
    }

    function getMyFollow(){
        [$page,$limit] = $this->getPage($this->request->param());
        $list = $this->userFollowModel->where('user_id',$this->request->user_id)
            ->order('id desc')
            ->page($page,$limit)
            ->select();
        foreach ($list as &$val){
            $val['writer'] = $this->model->getFindById($val['writer_id'],'id,writer_name,writer_head_img,fans_num');
        }
        unset($val);
        return $list;
    }

    function apply(){
        if($this->request->user['is_writer'] == 1){
            $this->ERROR='已经是创作者了';
            return false;
        }
        $validate = new UserWriterVal();
        if(!$validate->scene('create')->check($this->param)){
            $this->ERROR = $validate->getError();
            return false;
        }
        //todo 验证验证码

        $info = $this->userWriterApplyModel->where('user_id',$this->request->user_id)->find();
        $param = $this->param;
        $param['mp3'] = implode(',',$param['mp3']??[]);
        $param['status'] = 10;
        $param['user_id'] = $this->request->user_id;
        Db::startTrans();
        try{
            if(empty($info)){
                $this->userWriterApplyModel->save($param);
            }else{
                $info->save($param);
            }
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            $this->ERROR = $exception->getMessage();
            return false;
        }

        return true;
    }

    function apply_info(){
        if($this->request->user['is_writer'] == 1){
            $this->ERROR='已经是创作者了';
            return false;
        }
        $info = $this->userWriterApplyModel
            ->where('user_id',$this->request->user_id)
            ->hidden(['create_time','update_time','delete_time','user_id'])
            ->find();
        $info['mp3'] = explode(',',$info['mp3']);
        return $info;
    }

    function getMyWater(){
        [$page,$limit] = $this->getPage($this->param);
        $query = $this->userWriterWaterModel->where('user_id',$this->request->user_id);
        $list = $query->order('id desc')
            ->page($page,$limit)
            ->field(['type','price','source','remark','music_type','create_time'])
            ->select();
        $count = $query->count();

        $result['data']=$list;
        $result['count']=$count;
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;

    }
    function getMyAmount(){
        $result['can_withdrawal'] = $this->userWriterWaterModel
            ->where('user_id',$this->request->user_id)
            ->sum('price');
        $result['today_income'] = $this->userWriterWaterModel
            ->where('user_id',$this->request->user_id)
            ->where('type',2)
            ->whereTime('create_time','today')
            ->sum('price');
        $result['all_income'] = $this->userWriterWaterModel
            ->where('user_id',$this->request->user_id)
            ->where('source',1)
            ->sum('price');
        $result['music'] = $this->userWriterWaterModel//DJ单曲
            ->where('user_id',$this->request->user_id)
            ->where('source',1)
            ->where('music_type',20)
            ->sum('price');
        $result['music_skewer'] = $this->userWriterWaterModel
            ->where('user_id',$this->request->user_id)
            ->where('source',1)
            ->where('music_type',50)
            ->sum('price');
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }
    function withdrawalApply(){
        $apply_price = $this->param['price']??0;
        if($apply_price <=0){
            $this->ERROR='请输入正确金额';
            return false;
        }
        $can_withdrawal = $this->userWriterWaterModel->where('user_id',$this->request->user_id)
            ->sum('price');
        if($can_withdrawal < $apply_price){
            $this->ERROR='提现金额不能大于可提现金额';
            return false;
        }
        $config = ConfigSingle::getInstance()->getConfig();
        if($config['writer_min_withdraw'] > $apply_price){
            $this->ERROR='最低提现金额为:'.$config['writer_min_withdraw'];
            return false;
        }
        $writer_withdraw_rate = $config['writer_withdraw_rate'];
        if($this->request->user['writer_withdraw_rate'] != -1){
            $writer_withdraw_rate = $this->request->user['writer_withdraw_rate'];
        }
        $shouxu_price = round(($apply_price *$writer_withdraw_rate)/100 , 2);
        $price = round($apply_price - $shouxu_price,2);
        Db::startTrans();
        try {
            $this->userWriterWaterModel->save([
                'user_id'=>$this->request->user_id,
                'type'=>1,
                'price'=>-$apply_price,
                'source'=>200,
                'remark'=>'申请提现：'.$apply_price.'元',
            ]);
            $this->UserWriterWithdrawModel->save([
                'user_id'=>$this->request->user_id,
                'sn'=>Snow::createOnlyId(),
                'price'=>$price,
                'apply_price'=>$apply_price,
                'shouxu_price'=>$shouxu_price,
            ]);
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            $this->ERROR=$exception->getMessage();
            return false;
        }
        return true;

    }
}